<?php
namespace  app\models;
require_once 'BaseModel.php';

class Skeys  extends BaseModel{
	
	/**
	 * jianhaomai
	 * 获取skey
	 * @param unknown_type $name
	 * @return unknown|NULL
	 */
	public static function getSkeys($appkey, $skey){
		//$appkey = mysql_real_escape_string($appkey);
		//$skey = mysql_real_escape_string($skey);
		$con = self::pdo_con();
		$sql = "select * from skeys where appkey ='{$appkey}' and skey='{$skey}' order by id asc limit 1;";
		foreach ($con->query($sql) as $row) {
			if(time() > strtotime($row['expired_at'])){
				//已经过期
				return null;
			}else{
				return $row;
			}
        }
        return null;
	}
	
	/**
	 * jiahaomai
	 * 生成skey保存在db
	 * @param unknown_type $user_id
	 * @param unknown_type $appid
	 */
	public static function saveSkey($user_id, $appkey){
		$user_id = intval($user_id);
	    $appkey = mysql_real_escape_string($appkey);
		$skey = strtoupper(md5(time() . mt_rand(0, 10000) . substr('abcdefg', mt_rand(0, 7))));
		$expired_at = date('Y-m-d H:i:s', strtotime('+1 hours'));
		$now = date('Y-m-d H:i:s');
		$con = self::pdo_con(); 
		//先删除旧的
		$remove_sql = "delete from skeys where user_id = {$user_id} and appkey = '{$appkey}'";
		$con->exec($remove_sql);
		$sql = "insert into skeys values(0, {$user_id}, '{$appkey}', '{$skey}', '{$expired_at}', '{$now}')";
		$con->exec($sql);
		return $skey;
	}
	
	
	/**
	 * 验证完skey后，删除，只使用一次
	 * @param unknown_type $appkey
	 * @param unknown_type $skey
	 */
	public static function delSkey($appkey, $skey){
		//$appkey = mysql_real_escape_string($appkey);
		//$skey = mysql_real_escape_string($skey);
		$con = self::pdo_con(); 
		$remove_sql = "delete from skeys where skey = '{$skey}' and appkey = '{$appkey}'";
		$con->exec($remove_sql);
	}
	
	
	
	
	
	
	
}
